#!/bin/bash

BINDIR=$(cd $(dirname $0) && pwd)

. ${BINDIR}/common
. ${BINDIR}/functions

if [ ! -d ${LOGDIR} ]
then
	mkdir -p ${LOGDIR}
	chown ${FPPUSER}.${FPPUSER} ${LOGDIR}
	chmod 775 ${LOGDIR}
fi

${SCRIPTDIR}/timezone_sync

WaitForInterfacesUp

if [ ! -f /etc/fpp/desktop ]; then
MaybeEnableTethering
fi

SLEEPSECS=$(getSetting bootDelay)
if [ "x${SLEEPSECS}" != "x" ]
then
    echo "FPP - Sleeping for ${SLEEPSECS} seconds"
	sleep ${SLEEPSECS}
fi


checkAudioConfig

aplay -l 2>&1 | grep -q "no soundcards"
HASSOUND=$?
echo "FPP - Configuring Audio: ${HASSOUND}"
if [ ${HASSOUND} -eq 0 ]; then
    modprobe -q snd-dummy
    aplay -l 2>&1 | grep -q "no soundcards"
    HASSOUND=$?
    if [ ${HASSOUND} -eq 1 ]; then
        echo "    Loaded snd-dummy"
    fi
fi
if [ ${HASSOUND} -eq 1 ]; then
    CARDID=$(getSetting AudioOutput)
    HASCARD=$(amixer -c ${CARDID} cset numid=3 1 2>&1  >/dev/null)
    ## if invlid, we can wait a few seconds to see if the card appears 
    if [[ $HASCARD == *"Invalid "* ]]; then
        sleep 1
        HASCARD=$(amixer -c ${CARDID} cset numid=3 1 2>&1  >/dev/null)
    fi
    if [[ $HASCARD == *"Invalid "* ]]; then
        sleep 1
        HASCARD=$(amixer -c ${CARDID} cset numid=3 1 2>&1  >/dev/null)
    fi
    if [[ $HASCARD == *"Invalid "* ]]; then
        sleep 1
        HASCARD=$(amixer -c ${CARDID} cset numid=3 1 2>&1  >/dev/null)
    fi
    if [[ $HASCARD == *"Invalid "* ]]; then
        cp /opt/fpp/etc/asoundrc.plain /root/.asoundrc
        CARDID=0
        setSetting "AudioOutput" "0"
    fi

    VOLUME=$(getSetting volume)
    if [ "x${VOLUME}" = "x" ]; then
        setSetting volume 70
        VOLUME=70
    fi

    # Pi needs a volume adjustment, in reality a lot of sound cards do, but we
    # don't want to put in a lot of special cases here so only handle the Pi
    CARD0STR=""
    CARDRATE=$(getSetting AudioFormat)
    if [ "${FPPPLATFORM}" = "Raspberry Pi" ]; then
        CARD0STR=$(aplay -l | grep "^card $CARDID" | sed -e 's/^card //' -e 's/:[^\[]*\[/:/' -e 's/\].*\[.*\].*//' | uniq | colrm 1 2 | colrm 5)
        if [ "$CARD0STR" == "bcm2" ]; then
            if [ "$CARDID" == "0"]; then
                VOLUME=$(echo "scale=2 ; ${VOLUME} / 2.0 + 50" | bc)
            fi
            setSetting AudioCard0Type $CARD0STR
        else 
            setSetting AudioCard0Type "unknown"
        fi
    else
        setSetting AudioCard0Type "unknown"
    fi
    
    if [ -f "/home/fpp/media/tmp/asoundrc" -a "$CARDID" == "0" ]; then
        # if the selected card is the built in card and the cape provides the required asoundrc
        # then we will use that.   Various capes may need special alsa configuration in order
        # to properly be able to have volume control work
        cp -f "/home/fpp/media/tmp/asoundrc" /root/.asoundrc
    else
        # reset back to default asoundrc and set the card
        rm -f /root/.asoundrc
        if [ "$CARD0STR" == "bcm2" ]; then
            # dmix doesn't work with the Pi's onboard audio connector
            cp /opt/fpp/etc/asoundrc.plain /root/.asoundrc
        else
            cp /opt/fpp/etc/asoundrc.dmix /root/.asoundrc
        fi
    fi
    
    echo "Setting /root/.asoundrc to use card id ${CARDID}"
    sed -i "s/card [0-9]/card ${CARDID}/" /root/.asoundrc
    case "${CARDRATE}" in
    "1" | "2" | "3")
       sed -ie 's/rate *44100/rate 44100/' /root/.asoundrc
       ;;
    "4" | "5" | "6")
       sed -ie 's/rate *44100/rate 48000/' /root/.asoundrc
       ;;
    "7" | "8" | "9")
       sed -ie "s/rate *44100/rate 96000/" /root/.asoundrc
       ;;
    esac

    MIXERDEVICES=$(amixer -c $CARDID scontrols | head -1 | cut -f2 -d"'")
    if [ "x${MIXERDEVICES}" == "x" ]; then
        # for some sound cards, the mixer devices won't show up
        # until something is played.  Play one second of silence
        aplay -d 1 /opt/fpp/media/silence_5sec.wav >> /dev/null 2>&1  &
        sleep 0.2
        MIXERDEVICES=$(amixer -c $CARDID scontrols | head -1 | cut -f2 -d"'")
    fi

    MIXERDEVICES=$(amixer -c $CARDID scontrols | cut -f2 -d"'")
    MIXERDEVICE=$(getSetting AudioMixerDevice)
    if [ -z "${MIXERDEVICE}" ]; then
        MIXERDEVICE=$(amixer -c $CARDID scontrols | head -1 | cut -f2 -d"'")
        setSetting AudioMixerDevice $MIXERDEVICE
    else
        MD=$(echo $MIXERDEVICES | xargs -n1 echo | grep $MIXERDEVICE)
        if [ "$MD" != "$MIXERDEVICE" ]; then
            echo "Did not find mixer device $MIXERDEVICE, resetting to default"
            MIXERDEVICE=$(amixer -c $CARDID scontrols | head -1 | cut -f2 -d"'")
            setSetting AudioMixerDevice $MIXERDEVICE
    fi
    fi

    amixer -c ${CARDID} set ${MIXERDEVICE} ${VOLUME}% > /dev/null 2>&1
    
    CARDTYPE=$(aplay -l | grep "^card $CARDID" | sed -e 's/^card //' -e 's/:[^\[]*\[/:/' -e 's/\].*\[.*\].*//'  -e 's@/@@' -e 's/=//' | uniq | colrm 1 2)
    echo "Found card type: $CARDTYPE"
    setSetting AudioCardType "$CARDTYPE"
fi



if [ "${FPPPLATFORM}" = "Raspberry Pi" ]
then
    echo "FPP - Setting up SPI"
    modprobe spidev

    if [ ! -e /dev/spidev0.0 ]; then
        sleep 0.5
    fi

	# See if we have any Falcon hardware on the SPI port
	echo "FPP - Checking for Falcon hardware on SPI port"
	detectFalconHardware
fi

# Print/Say the IP address
if [ -f /usr/bin/flite ]
then
    _IP=$(hostname -I) || true
    if [ "$_IP" ]; then
        echo "FPP - Found IP(s): $_IP"

        DISABLEIPANN=$(getSetting disableIPAnnouncement)
        if [ "x${DISABLEIPANN}" != "x1" ]
        then
            FLITESTR="I Have Found The Following I P Addresses"
            for ELEMENT in ${_IP// / }; do
                case "${ELEMENT}" in
                "192.168.6.2" | "192.168.7.2" | "192.168.8.1" )
                    ;;
                * )
                    FLITESTR+=", ${ELEMENT} "
                    ;;
                esac
            done
            flite -voice awb -t "${FLITESTR}" &
            echo "${FLITESTR}"
        fi
    else
        echo "FPP - No IP(s) found"
    fi
fi

HOSTNAME=$(getSetting HostName)
if [ "${HOSTNAME}" = "" ]; then
    HOSTNAME=$(hostname)
    if [ "${HOSTNAME}" != "" ]; then
        setSetting HostName ${HOSTNAME}
    fi
fi
